import React from 'react';
import {injectIntl} from './intl';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {
    PAGE_TEN,
    TABLE,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH,
    DATE_FORMAT,
    DATETIME_FORMAT,
} from '../constants';
import {Link} from 'react-router-dom';
import {hasPermissions, conventSorter} from './utils';

import {paymentType, transportType, partOrderPriceTerms, partContractInvoiceStatus} from '../Enum';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';
import {PERMISSION} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
export class TablePanel extends React.PureComponent {
    state = {
        loading: false
    };
    handleAbandon = id => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };

    handleUploadSAP = id => {
        this.setState({
            loading: true
        });
        this.props.onClickUploadSAP(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({...conventSorter(sorter),
                pageIndex: PAGE_TEN.index});
    };
    render() {
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '发票编号'
                }),
                sorter: true,
                dataIndex: 'code',
                render: (text, record) => (
                    <Link key="detail" to={routes.detail.format(record.id)}>
                        {text}
                    </Link>
                )
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.shipmentType',
                    defaultMessage: '发运方式'
                }),
                dataIndex: 'shipmentType',
                render: text => conventEnumValueToString(transportType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.paymentType',
                    defaultMessage: '付款方式'
                }),
                dataIndex: 'paymentType',
                render: text => conventEnumValueToString(paymentType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.priceTerms',
                    defaultMessage: '价格条款'
                }),
                dataIndex: 'priceTerms',
                render: text => conventEnumValueToString(partOrderPriceTerms, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.totalQuantity',
                    defaultMessage: '备件总数量'
                }),
                dataIndex: 'totalQuantity',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.totalAmount',
                    defaultMessage: '备件总金额'
                }),
                dataIndex: 'totalAmount',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.totalDiscount',
                    defaultMessage: '折扣总金额'
                }),
                dataIndex: 'totalDiscount',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.invoiceAmount',
                    defaultMessage: '发票金额'
                }),
                dataIndex: 'invoiceAmount',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(partContractInvoiceStatus, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.invoicedDate',
                    defaultMessage: '开票日期'
                }),
                dataIndex: 'invoicedDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.createTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [

                        {
                            id: PERMISSION.uploadSAP,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="abandon"
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleUploadSAP}>
                                    <a key="uploadSAP">
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.uploadSAP',
                                            defaultMessage: '上传SAP'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.uploadSAP) && hasPermissions(r.options, PERMISSION.uploadSAP))
                        },
                        {
                            id: PERMISSION.update,
                            children: (
                                <Link key="update" to={routes.update.format(r.id)}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                        },
                        {
                            id: PERMISSION.abandon,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="abandon"
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleAbandon}>
                                    <a key="abandon">
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.abandon',
                                            defaultMessage: '作废'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                        },
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }
        ];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}/>
            </div>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickUploadSAP: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {
    tableSearch,
    onClickAbandon,
    onClickUploadSAP,
} from './actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE_TEN.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickAbandon: id =>
        dispatch(onClickAbandon(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE_TEN.index
            }));
            return success;
        }),
    onClickUploadSAP: id =>
        dispatch(onClickUploadSAP(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE_TEN.index
            }));
            return success;
        }),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(TablePanel));
